package git.soulbgm.controller;

import git.soulbgm.common.enums.CodeEnum;
import git.soulbgm.service.LoginService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 身份验证控制器
 *
 * @author SoulBGM
 * @date 2024/02/22
 */
@RestController
public class AuthController {

    private static final String HEADER_URI_TOKEN = "at_";
    private static final String HEADER_URI = "X-Original-URI";
    private static final String TOKEN_HEADER = "Authorization";
    private final LoginService loginService;

    public AuthController(LoginService loginService) {
        this.loginService = loginService;
    }

    @GetMapping("/auth/token")
    public void auth(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(TOKEN_HEADER);
        String uri = request.getHeader(HEADER_URI);
        if (token == null && uri != null && !"".equals(uri.trim()) && uri.contains(HEADER_URI_TOKEN)) {
            token = uri.split(HEADER_URI_TOKEN)[1];
        }
        if (token == null) {
            response.setStatus(CodeEnum.UNKNOWN_ACCOUNT.getCode());
            return;
        }
        String[] split = token.split("_-_");
        if (split.length != 2) {
            response.setStatus(CodeEnum.UNKNOWN_ACCOUNT.getCode());
            return;
        }

        String username = split[0];
        String password = split[1];

        boolean result = loginService.login(username, password);
        if (!result) {
            response.setStatus(CodeEnum.USERNAME_OR_PASSWORD_IS_INCORRECT.getCode());
            return;
        }
        response.setStatus(CodeEnum.LOGIN_SUCCESS.getCode());
    }
}
